﻿using Newtonsoft.Json.Linq;
using PubSub;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LD.Host.WIP
{
    public class WipHelper
    {
        private Dictionary<int, WipModel> data;

        public WipHelper()
        {

        }
        public void Init()
        {
            data = (Dictionary<int, WipModel>)Cache.GetCache(CONST.SYS_WIP);
            if (data == null)
                data = new Dictionary<int, WipModel>
            {
                { 8, new WipModel(){Hour=8 }  },
                { 10, new WipModel() {Hour=10 } },
                { 12, new WipModel() {Hour=12 } },
                { 14, new WipModel() {Hour=14 } },
                { 16, new WipModel() {Hour=16 } },
                { 18, new WipModel() {Hour=18 } },
                { 20, new WipModel() {Hour=20 } },
                { 22, new WipModel() {Hour=22 } },
                { 0, new WipModel() {Hour=0 } },
                { 2, new WipModel() {Hour=2 } },
                { 4, new WipModel() {Hour=4 } },
                { 6, new WipModel() {Hour=6 } }
            };
        }
        public Dictionary<int, WipModel> GetData
        {
            get
            {
                return data;
            }
        }
        public void SetWip(ResultType result)
        {
            int hour = (DateTime.Now.Hour % 2) == 0 ? DateTime.Now.Hour : DateTime.Now.Hour - 1;
            var curData = data.Where(p => p.Key == hour).FirstOrDefault();
            if (result == ResultType.OK)
                curData.Value.Ok++;
            else
                curData.Value.Ng++;

            EndTime = DateTime.Now;
            Hub.Default.PublishAsync(new NotityHandler()
            {
                NtType = NotityType.WIP,
                Data = hour,
                Tag = (int)result
            });

            Cache.SetCache(CONST.SYS_WIP, data);
            Cache.SaveCache();
        }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }
    }
    [Serializable]
    public class WipModel
    {
        public int Hour { get; set; }
        public int Ok { get; set; } = 0;
        public int Ng { get; set; } = 0;
    }
}
